package com.suxin.validator.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author Tang
 * @classname MaxConstraintValidator
 * @description [ 自定义校验器 ]
 * @date 2023/1/7 14:55
 */
public class MaxConstraintValidator implements ConstraintValidator<MaxAnnotation,Integer> {

    boolean isRequire;
    Class<?>[] groups;
    String message;
    Integer maxValue;

    @Override
    public void initialize(MaxAnnotation constraintAnnotation) {
        this.isRequire = constraintAnnotation.isRequire();
        this.groups = constraintAnnotation.groups();
        this.message = constraintAnnotation.message();
        this.maxValue = constraintAnnotation.max();
    }

    /**
     * isValid
     * @param value 要检验的值
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        if (this.isRequire && value > this.maxValue) {
            // 禁用默认的提示
            context.disableDefaultConstraintViolation();
            // 重新构建提示
            context.buildConstraintViolationWithTemplate(String.format("%d 大于 %d", value, maxValue))
                    .addConstraintViolation();
            return false;
        }
        return true;
    }

}
